package com.atguigu.flink.state;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2023/4/10
 *
 *   计算每种传感器的平均水位
 *          输入： 水位 Integer
 *          输出: 平均水位  Double
 *
 *          ReducingState无法实现，必须要求输入和输出是同一类型
 *
 */
public class Demo8_KeyedAggregateState
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

                env
                   .socketTextStream("hadoop102", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   .process(new KeyedProcessFunction<String, WaterSensor, String>()
                   {

                       private AggregatingState<Integer, Double> avgVC;

                       /*
                                                                          keyed state，都是在当前Task初始化时，从备份中获取状态。

                                                                          avgVc =  sumVc / count
                                                                      */
                       @Override
                       public void open(Configuration parameters) throws Exception {
                           avgVC = getRuntimeContext().getAggregatingState(new AggregatingStateDescriptor<>("avgVC",
                               new AggregateFunction<Integer, Tuple2<Double, Integer>, Double>()
                               {
                                   @Override
                                   public Tuple2<Double, Integer> createAccumulator() {
                                       return Tuple2.of(0d, 0);
                                   }

                                   @Override
                                   public Tuple2<Double, Integer> add(Integer value, Tuple2<Double, Integer> accumulator) {
                                       accumulator.f0 = accumulator.f0 + value;
                                       accumulator.f1 = accumulator.f1 + 1;
                                       return accumulator;
                                   }

                                   @Override
                                   public Double getResult(Tuple2<Double, Integer> accumulator) {
                                       return accumulator.f0 / accumulator.f1;
                                   }

                                   //不实现
                                   @Override
                                   public Tuple2<Double, Integer> merge(Tuple2<Double, Integer> a, Tuple2<Double, Integer> b) {
                                       return null;
                                   }
                               }
                               , Types.TUPLE(Types.DOUBLE, Types.INT)));
                       }

                       @Override
                       public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                          //把需要聚合的数据加入状态，自动聚合
                           avgVC.add(value.getVc());

                           out.collect(ctx.getCurrentKey() + "sumvc是: "+avgVC.get());

                       }
                   })
                   .print();

                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }


}
